﻿using JNPF.Basics.Models;
using JNPF.Utils;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace JNPF.Basics.Logic
{
    /// <summary>
    /// 企业号组织
    /// 版 本：V3.0.0
    /// 版 权：引迈信息技术有限公司（https://www.jnpfsoft.com）
    /// 作 者：JNPF开发平台组
    /// 日 期：2018-08-06 
    /// </summary>
    public class QYDepartmentBll
    {
        private QYDepartmentIService service = new QYDepartmentService();
        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<QYDepartmentEntity>> GetList()
        {
            try
            {
                return await service.GetList();
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 部门列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<QYDepartmentEntity>> GetSyncList()
        {
            try
            {
                return await service.GetSyncList();
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 列表
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<List<QYDepartmentEntity>> GetListByUserId(string userId)
        {
            try
            {
                return await service.GetListByUserId(userId);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 同步数据
        /// </summary>
        /// <param name="organizelist">部门列表</param>
        public async Task Synchronization(List<OrganizeEntity> organizelist)
        {
            var userId = UserProvider.Instance.Get().UserId;
            var config = await new SysConfigBll().GetInfo("QYHConfig");
            #region
            try
            {
                #region 删除
                var syncList = await service.GetSyncList();
                if (syncList.Count > 0)
                {
                    foreach (QYDepartmentEntity departmentEntity in syncList)
                    {
                        if (organizelist.FindAll(t => t.Id == departmentEntity.OrganizeId).Count == 0)
                        {
                            var resultBool = new WeChatQYHelper(config.QYH_CorpId, config.QYH_CorpSecret).DeleteDepartment(departmentEntity.WeChatDeptId);
                            if (resultBool == true)
                            {
                                departmentEntity.SubmitState = "删除";
                                await service.Delete(departmentEntity);
                            }
                        }
                    }
                }
                #endregion

                #region 创建-编辑
                if (organizelist.Count > 0)
                {
                    var orgList = await service.GetList();
                    var index = organizelist.Count;
                    foreach (OrganizeEntity organizeEntity in organizelist)
                    {
                        if (syncList.FindAll(s => s.OrganizeId == organizeEntity.Id).Count == 0)
                        {
                            #region 创建
                            int order = index--;
                            syncList = await service.GetSyncList();
                            int? parentId = organizeEntity.ParentId == "0" ? 1 : syncList.Find(t => t.OrganizeId == organizeEntity.ParentId).WeChatDeptId;
                            //调用微信企业号接口同步
                            var id = new WeChatQYHelper(config.QYH_CorpId, config.QYH_CorpSecret).CreateDepartment(organizeEntity.FullName, Convert.ToInt64(parentId), order);
                            if (!string.IsNullOrEmpty(id.ToString()))
                            {
                                QYDepartmentEntity departmentEntity = new QYDepartmentEntity();
                                departmentEntity.Id = CommonHelper.Guid;
                                departmentEntity.OrganizeId = organizeEntity.Id;
                                departmentEntity.EnabledMark = organizeEntity.EnabledMark;
                                departmentEntity.LastModifyTime = organizeEntity.LastModifyTime;
                                departmentEntity.Category = organizeEntity.Category;
                                departmentEntity.Description = organizeEntity.Description;
                                departmentEntity.EnCode = organizeEntity.EnCode;
                                departmentEntity.FullName = organizeEntity.FullName;
                                departmentEntity.ManagerId = organizeEntity.ManagerId;
                                departmentEntity.PropertyJson = organizeEntity.PropertyJson;
                                departmentEntity.ParentId = organizeEntity.ParentId;
                                departmentEntity.WeChatParentId = parentId;
                                departmentEntity.WeChatDeptId = id.ToInt();
                                departmentEntity.CreatorTime = DateTime.Now;
                                departmentEntity.SyncState = 1;
                                departmentEntity.CreatorUserId = userId;
                                departmentEntity.Order = order;
                                departmentEntity.SubmitState = "创建";
                                await service.Create(departmentEntity);
                            }
                            #endregion
                        }
                        else
                        {
                            #region 编辑
                            var organizeLastEntity = orgList.Find(o => o.Id == organizeEntity.Id);
                            if (organizeLastEntity.LastModifyTime.ToDate().ToString("yyyy-MM-dd") != "1900-01-01")
                            {
                                var syncOrganize = syncList.FindAll(s => s.OrganizeId == organizeEntity.Id);
                                foreach (var departmentEntity in syncOrganize)
                                {
                                    var parentId = syncList.Find(t => t.OrganizeId == organizeEntity.ParentId).WeChatDeptId;
                                    var resultBool = new WeChatQYHelper(config.QYH_CorpId, config.QYH_CorpSecret).UpdateDepartment(departmentEntity.WeChatDeptId, organizeEntity.FullName, parentId, departmentEntity.Order);
                                    if (resultBool == true)
                                    {
                                        departmentEntity.LastModifyTime = organizeEntity.LastModifyTime;
                                        departmentEntity.LastModifyUserId = userId;
                                        departmentEntity.SubmitState = "编辑";
                                        await service.Update(departmentEntity);
                                    }
                                }
                            }
                            #endregion
                        }
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
            #endregion
        }
    }
}
